package utils

import (
	"fmt"
	"github.com/sirupsen/logrus"
	"gopkg.in/yaml.v2"
	"io/ioutil"
	"log"
	"time"
)

type ClientConf struct {
	Server string `yaml:"server"`
}

type ServerConf struct {
	LogConf     LogConfig   `yaml:"log"`
	MysqlConf   MysqlConfig `yaml:"mysql"`
	WhiteList []string `yaml:"white"`
	ThirdApi 	ThirdApiConf `yaml:"third-api"`
	Listen 	string `ysml:"listen"`
	FileServer FileServerConf `yaml:"file-server"`
	ConfCenter ConfCenterConf `yaml:"conf-center"`
}

type FileServerConf struct {
	Rpm1 	string `yaml:"rpm1"`
	Rpm2 	string `yaml:"rpm2"`

	Log 	string `yaml:"log"`
}

type ThirdApiConf struct {
	N9e	string `yaml:"n9e"`
	Token string `yaml:"token"`
}

type LogConfig struct{
	Level logrus.Level `yaml:"level"`
	Name string `yaml:"name"`
	RotateTime time.Duration `yaml:"rotateTime"`
	MaxCount int `yaml:"maxCount"`
}

type MysqlConfig struct{
	Host string     `yaml:"host"`
	Port int        `yaml:"port"`
	DbName string   `yaml:"dbname"`
	User string     `yaml:"user"`
	Passwd string   `yaml:"passwd"`
}

type ConfCenterConf struct {
	Server string `yaml:server`
}

func GetServerConfiguration(path string) (*ServerConf, error) {
	data, err := ioutil.ReadFile(path)
	if err != nil {
		return nil,err
	}
	var s ServerConf
	err = yaml.Unmarshal(data, &s)
	if err != nil {
		return nil,err
	}
	if err != nil{
		fmt.Println("err:",err.Error())
	}
	return &s,nil
}

func GetClientConfiguration(path string) (*ClientConf, error) {
	data, err := ioutil.ReadFile(path)
	if err != nil {
		return nil,err
	}
	var c ClientConf
	err = yaml.Unmarshal(data, &c)
	if err != nil {
		return nil,err
	}
	if err != nil{
		fmt.Println("err:",err.Error())
	}
	return &c,nil
}

type DataStruct struct {
	Data []Data `yaml:"data"`

}

type Data struct {
	Server string	`yaml:"Server"`
	PortCheck	string	`yaml:"PortCheck"`
	ServerName []string	`yaml:"ServerName"`
	LogDir string 	`yaml:"LogDir"`
	LogHead string   `yaml:"LogHead"`
	RpmName []string `yaml:"RpmName"`
}

var DataYaml string

func GetDataConfiguration(servername string)(Data,error){
	d := DataStruct{}
	result := Data{}
	data, err := ioutil.ReadFile(DataYaml)
	if err != nil {
		return result,err
	}
	err = yaml.Unmarshal(data, &d)
	if err != nil {
		fmt.Println("err:",err.Error())
		return result,err
	}
	log.Println(d)
	for _,v := range d.Data{
		if v.Server== servername{
			result = v
			return result,nil
		}
	}
	return result,nil
}

func GetServerNameSlice()(re []string){
	data, err := ioutil.ReadFile(DataYaml)
	if err != nil {
		log.Println("获取所有服务名时，加载配置文件失败")
		return
	}
	d := DataStruct{}
	err = yaml.Unmarshal(data, &d)
	if err != nil {
		log.Println("err:",err.Error())
		return
	}
	for _,serve := range d.Data{
		re = append(re, serve.Server)
	}
	return
}